import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as apiLogin, getUserInfo as apiGetUserInfo, logout as apiLogout } from '@/api/user'
import type { UserInfo } from '@/types/user'
import { type UserRole } from '@/types/user'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { useWallpaperStore } from './wallpaper'

export const useUserStore = defineStore('user', () => {
  // Token
  const token = ref<string>('')
  
  // 用户信息
  const userInfo = ref<UserInfo | null>(null)
  
  // 权限列表
  const permissions = ref<string[]>([])
  
  // 计算属性：用户是否已登录
  const isLoggedIn = computed(() => !!token.value)
  
  // 计算属性：用户名
  const username = computed(() => userInfo.value?.username || '')
  
  // 计算属性：用户角色
  const roles = computed(() => userInfo.value?.roles || [])
  
  // 计算属性：用户头像
  const avatar = computed(() => userInfo.value?.avatar || '')
  
  // 登录
  const login = async (loginData: { username: string, password: string, remember?: boolean }) => {
    try {
      const res = await apiLogin(loginData)
      token.value = res.token
      
      // 获取用户信息
      await getUserInfo()
      
      // 更新壁纸状态
      const wallpaperStore = useWallpaperStore()
      await wallpaperStore.onUserLogin()
      
      // 跳转到主页
      const redirect = router.currentRoute.value.query.redirect as string
      router.push(redirect || '/workspace')
      
      return true
    } catch (error) {
      clearUserInfo()
      throw error
    }
  }
  
  // 获取用户信息
  const getUserInfo = async () => {
    if (!token.value) {
      clearUserInfo()
      return null
    }
    
    try {
      const userInfoData = await apiGetUserInfo()
      userInfo.value = userInfoData.user
      
      // 设置权限
      if (userInfo.value?.roles) {
        setPermissions(userInfo.value.roles)
      }
      
      return userInfo.value
    } catch (error) {
      clearUserInfo()
      throw error
    }
  }
  
  // 登出
  const logout = async () => {
    try {
      if (token.value) {
        await apiLogout()
      }
    } catch (error) {
      console.error('登出请求失败', error)
    } finally {
      // 清除用户信息
      clearUserInfo()
      
      // 更新壁纸状态
      const wallpaperStore = useWallpaperStore()
      wallpaperStore.onUserLogout()
      
      // 跳转到登录页
      router.push('/login')
    }
  }
  
  // 设置权限
  const setPermissions = (roles: UserRole[]) => {
    const perms: string[] = []
    
    // 根据角色设置权限
    roles.forEach(role => {
      switch (role) {
        case UserRole.ADMIN:
          perms.push('admin')
          perms.push('user:manage')
          perms.push('app:manage')
          perms.push('system:manage')
          break
        case UserRole.USER:
          perms.push('user')
          perms.push('app:use')
          break
        case UserRole.DEVELOPER:
          perms.push('developer')
          perms.push('app:develop')
          perms.push('app:publish')
          break
      }
    })
    
    permissions.value = [...new Set(perms)]
  }
  
  // 清除用户信息
  const clearUserInfo = () => {
    token.value = ''
    userInfo.value = null
    permissions.value = []
  }
  
  // 检查是否有权限
  const hasPermission = (permission: string) => {
    if (!permissions.value.length) return false
    return permissions.value.includes(permission)
  }
  
  // 初始化状态，从localStorage加载token
  const initUserState = async () => {
    const savedToken = localStorage.getItem('token')
    if (savedToken) {
      token.value = savedToken
      try {
        await getUserInfo()
      } catch (error) {
        ElMessage.error('登录已过期，请重新登录')
        clearUserInfo()
      }
    }
  }
  
  return {
    token,
    userInfo,
    permissions,
    isLoggedIn,
    username,
    roles,
    avatar,
    login,
    logout,
    getUserInfo,
    hasPermission,
    initUserState,
    clearUserInfo
  }
}) 